/*
 * @Author: xiaozhuang-c-language 3535851673@qq.com
 * @Date: 2025-10-12 16:26:23
 * @LastEditors: xiaozhuang-c-language 3535851673@qq.com
 * @LastEditTime: 2025-10-12 16:34:43
 * @FilePath: /zhuang/linux-study/mmapTest/MyMalloc.cc
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include <cassert>
#include <cstddef>
#include <cstdio>
#include <cstring>
#include <ostream>
#include <sys/mman.h>
#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
using namespace std;

void* my_malloc(size_t size)
{
    //大小size要合法
  assert(size > 0);
  void* addr = ::mmap(nullptr, size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1,0);
  if(addr == MAP_FAILED)
  {
    std::cerr << "my_malloc: 申请size空间失败!" << std::endl;
    return nullptr;
  }
  return addr;
}

void my_free(void* addr,size_t size)
{
    //size和申请空间不能为空
   assert(addr && size > 0);
   if(::munmap(addr, size) == -1)
   {
      printf("释放空间%p失败！",addr);
      return;
   }
}

int main()
{
    char* ptr = (char*)my_malloc(1024);
    if(nullptr == ptr)
    {
        std::cerr << "malloc failed" << std::endl;
        return 1;
    }
    //使用分配的内存(简单打印指针的值)
    printf("Allocated memory at address:%p \n",ptr);

    memset(ptr, 'A', 1024);

    //
    for(int i = 0 ; i < 1024;i++)
    {
        printf("%c ",ptr[i]);
        fflush(stdout);
        sleep(1);
    }
    //释放空间
    my_free(ptr, 1024);
    return 0;
}